//
//  ConsulationV2AskViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/1.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "ConsulationV2AskViewController.h"

#import <PYPhotoBrowser/PYPhotoBrowser.h>
#import <TZImagePickerController/TZImagePickerController.h>

#import "EPAlertViewController.h"
#import "PayNumViewController.h"

@interface ConsulationV2AskViewController () <PYPhotosViewDelegate, TZImagePickerControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) ConsulationV2AskViewModel* viewModel;

// UI
//@property (weak, nonatomic) UILabel *addressLabel;

//IBOutlet
@property (weak, nonatomic) IBOutlet UITextField* titleTF;
@property (weak, nonatomic) IBOutlet UITextField* giveGoldTF;
@property (weak, nonatomic) IBOutlet UIView* textView;
@property (weak, nonatomic) IBOutlet UIView* imagesView;
@property (weak, nonatomic) IBOutlet UIButton* confirmBtn;

@end

@implementation ConsulationV2AskViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    self.hidesBottomBarWhenPushed = YES;
    
//    UIBarButtonItem *backItem = [UIBarButtonItem mh_itemWithImageName:@"icon_back_hei" highImageName:@"icon_back_hei" target:self action:@selector(_backButton)];
//    //这里可以设置导航栏的左右按钮 统一管理方法
//    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x) {
        @strongify(self)
        
    }];
}

- (void)initUI
{
    
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        UserManagerV2* userMgr = [UserManagerV2 sharedUserManagerV2];
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self)
        
        //重置 更新 frame
        [self _setupTextView];
        [self _setupImagesView];
    }];
    
    RAC(self.viewModel, askTitle) = [self.titleTF rac_textSignal];
    RAC(self.viewModel, giveGold) = [self.giveGoldTF rac_textSignal];
    
    // 图片编辑
    [RACObserve(self.viewModel, uploadImgs) subscribeNext:^(id x)
     {
         @strongify(self);
         
         PYPhotosView* photosView = [self.imagesView viewWithTag:10];
         if (photosView != nil)
         {
             photosView.images = x;
         }
         
         NSInteger imgCount = [x count] + 1;
         imgCount = imgCount>1?1:imgCount;
         NSInteger imgColNum = 3;
         CGFloat imgOffset = 16;
         CGFloat imgSize = (self.imagesView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
         
         NSInteger row = imgCount/3 + (imgCount%3>0?1:0);
         CGFloat viewHeight = imgSize*row + imgOffset*(row - 1);
         //修改约束
         for (NSLayoutConstraint* curConstraint in self.imagesView.constraints)
         {
             if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
             {
                 curConstraint.constant = viewHeight;
                 break;
             }
         }
     }];
    
    self.viewModel.showImgPickerCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                                       {
                                           @strongify(self)
                                           
                                           [self showImgPicker];
                                           
                                           return [RACSignal empty];
                                       }];
    
    [[self rac_signalForSelector:@selector(photosView:didAddImageClickedWithImages:) fromProtocol:@protocol(PYPhotosViewDelegate)] subscribeNext:^(id x)
     {
         @strongify(self)
         
         [self.viewModel.showImgPickerCmd execute:nil];
     }];
    
    [[self rac_signalForSelector:@selector(photosView:didDeleteImageIndex:) fromProtocol:@protocol(PYPhotosViewDelegate)] subscribeNext:^(id x)
     {
         @strongify(self);
         
         RACTuple* tuple = x;
         NSNumber* delImgIndexValue = tuple.second;
         
         [self.viewModel.deleteImgCmd execute:delImgIndexValue];
     }];
    
    // TZ图片选择回调
    RACSignal* tzChooseImagePickerSignal = [[self rac_signalForSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:) fromProtocol:@protocol(TZImagePickerControllerDelegate)] replay];
    [tzChooseImagePickerSignal subscribeNext:^(id x)
     {
         @strongify(self);
         
         RACTuple* tuple = x;
         
         NSArray* photos = tuple.second;
         
         [self.viewModel.addImgCmd execute:photos];
     }];
    
    // 图片选择回调
    RACSignal* chooseImagePickerSignal = [[self rac_signalForSelector:@selector(imagePickerController:didFinishPickingMediaWithInfo:) fromProtocol:@protocol(UIImagePickerControllerDelegate)] replay];
    
    [chooseImagePickerSignal subscribeNext:^(id x) {
        @strongify(self)
        
        RACTuple* tuple = x;
        
        UIImagePickerController* picker = tuple.first;
        NSDictionary* info = tuple.second;
        
        // 从info中将图片取出，并加载到imageView当中
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        [self.viewModel.addImgCmd execute:@[image]];
        
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    [[self rac_signalForSelector:@selector(imagePickerControllerDidCancel:) fromProtocol:@protocol(UIImagePickerControllerDelegate)] subscribeNext:^(id x) {
        @strongify(self)
        
        RACTuple* tuple = x;
        
        UIImagePickerController* pickerC = tuple.first;
        
        [pickerC dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    // 提交按钮
    [[self.confirmBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [MBProgressHUD mh_showProgressHUD:@"提交中..."];
        
        [self.viewModel.submitCmd execute:nil];
    }];
    [[self.viewModel.submitCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         [self.navigationController popViewControllerAnimated:YES];
         
         [MBProgressHUD mh_showTips:x];
     }];
    [[self.viewModel.submitCmd.errors deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         NSError* error = x;
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             if ([error.userInfo[SUCommandErrorUserInfoKey] isEqualToString:@"生态币不足"])
             {
                 [self _presentSTBBZAlertVC];
             }
             else
             {
                 [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             }
             
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
}

- (void)_setupTextView
{
    YYTextView* tView = [[YYTextView alloc] initWithFrame:(CGRect) {0, 0, self.textView.frame.size}];
    tView.font = [UIFont systemFontOfSize:16.0f];
    tView.placeholderFont = [UIFont systemFontOfSize:16.0f];
    tView.placeholderText = @"填写你想提问的问题";
    tView.placeholderTextColor = UIColorHex(#e0e0e0);
    tView.returnKeyType = UIReturnKeyDone;
    [self.textView addSubview:tView];
    
    RAC(self.viewModel, content) = RACObserve(tView, text);
}

- (void)_setupImagesView
{
    // 图片添加
    UIView* certImagesView = self.imagesView;
    [certImagesView removeAllSubviews];
    {
        NSInteger imgColNum = 3;
        
        // 计算大小
        CGFloat imgOffset = 16;
        CGFloat imgSize = (certImagesView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
        
        NSMutableArray* imgs = [NSMutableArray array];
        PYPhotosView *photosView = [PYPhotosView photosViewWithImages:imgs];
        photosView.photosState = PYPhotosViewStateWillCompose;
        photosView.photosMaxCol = 3;
        photosView.imagesMaxCountWhenWillCompose = 1;
        photosView.autoLayoutWithWeChatSytle = NO;
        photosView.oneImageFullFrame = NO;
        photosView.photoWidth = imgSize;
        photosView.photoHeight = imgSize;
        photosView.photoMargin = imgOffset;
        photosView.delegate = self;
        
        NSInteger row = 1;
        photosView.frame = (CGRect) {0, 0, certImagesView.frame.size.width, imgSize*row + imgOffset*(row - 1)};
        photosView.tag = 10;
        [certImagesView addSubview:photosView];
        //修改约束
        for (NSLayoutConstraint* curConstraint in certImagesView.constraints)
        {
            if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
            {
                curConstraint.constant = photosView.frame.size.height;
                
                break;
            }
        }
    }
}

#pragma mark - 功能
- (void)showImgPicker
{
    // 创建UIImagePickerController实例
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    // 设置代理
    imagePickerController.delegate = self;
    // 是否允许编辑（默认为NO）
    imagePickerController.allowsEditing = NO;
    
    // 创建一个警告控制器
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 设置警告响应事件
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 设置照片来源为相机
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        // 设置进入相机时使用前置或后置摄像头
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        
        // 展示选取照片控制器
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }];
    
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        [self presentViewController:imagePickerController animated:YES completion:^{}];
        //MaxImagesCount  可以选着的最大条目数
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 - self.viewModel.uploadImgs.count delegate:self];
        imagePicker.navigationBar.tintColor = UIColorHex(#000000);
        [imagePicker setBarItemTextColor:UIColorHex(#000000)];
        
        // 是否显示可选原图按钮
        imagePicker.allowPickingOriginalPhoto = NO;
        // 是否允许显示视频
        imagePicker.allowPickingVideo = NO;
        // 是否允许显示图片
        imagePicker.allowPickingImage = YES;
        
        // 这是一个navigation 只能present
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        // 添加警告按钮
        [alert addAction:cameraAction];
    }
    
    [alert addAction:photosAction];
    [alert addAction:cancelAction];
    
    alert.popoverPresentationController.sourceView = self.view;
    alert.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    
    // 展示警告控制器
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 监听

//- (void)_backButton
//{
//    [self dismissViewControllerAnimated:YES completion:^{
//        
//    }];
//}

#pragma mark - 跳转
- (void)_presentSTBBZAlertVC
{
    @weakify(self);
    EPAlertViewModel* vm = [[EPAlertViewModel alloc] initWithParams:@{}];
    vm.strTitle = @"提示";
    vm.strContent = @"生态币不足，请前往充值";
    vm.strConfirm = @"前往";
    [vm.confirmCmd.executionSignals.switchToLatest subscribeNext:^(id x)
     {
         @strongify(self);
  
         [self _push2PayVC];
     }];
    EPAlertViewController* vc = [[EPAlertViewController alloc] initWithViewModel:vm];
    vc.view.backgroundColor = [UIColor clearColor];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    else
    {
        vc.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
    [self presentViewController:vc animated:YES completion:^
     {
         vc.view.backgroundColor = UIColorHex(#0000000f);
     }];
}

- (void)_push2PayVC
{
    PayNumViewModel* vm = [[PayNumViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"支付方式"}];
    PayNumViewController* vc = [[PayNumViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
